import axios from 'axios';

export default function fetch(url, param = {}, method = 'post', responseType = null) {
  param = JSON.stringify(param);
  return axios({
    method,
    headers: {
      'Content-Type': responseType === 'blob' ? 'application/x-www-form-urlencoded; charset=utf-8' : 'application/json',
      'Authorization': sessionStorage.getItem('token') || '',
    },
    responseType,
    url: url,
    data: param
  }).then(res => {
    return res.status === 200 ? Promise.resolve(res.data) : Promise.reject(res)
  }).then(res => {
    if (responseType === 'blob') {
      const thisUrl = window.URL.createObjectURL(new Blob([res],{type: "application/vnd.ms-excel;charset=utf-8"}))
      return thisUrl;
    }
    switch (+res.code) {
      case 200:
        res.data = res.data ? res.data : '操作成功';
        return Promise.resolve(res.data);
      case 300:
        if (+res.errorCode !== 300003) {
          return Promise.reject({ response: {
              status: 300,
              errorMsg: res.errorMsg
            } });
        }
        else {
          return Promise.reject(res.errorMsg)
        }
      case 400:
      case 500:
      case 600:
      default:
        return Promise.reject(res.errorMsg)
    }
  }).catch (e => {
    if (e.response) {
      const status = e.response.status;
      // if (status === 403) {
      //   router.push('/exception/403');
      //   return;
      // }´
      // if (status <= 504 && status >= 500) {
      //   router.push('/exception/500');
      //   return;
      // }
      // if (status >= 404 && status < 422) {
      //   router.push('/exception/404');
      // }
      if (status === 300) {
        window.g_app._store.dispatch({
          type: 'user/logout'
        });
        throw new Error('用户登录过期，请重新登录')
      }
    }
    throw new Error(e)
  })
}
